import { useRuntimeConfig } from '#imports'
import qs from 'qs'

// 后续需要如 FormData 再扩展
interface Config {
  url: string
  method?: string
  data?: any
  params?: any
  responseType?: 'json' | 'blob' | 'text' | 'raw'
  headers?: HeadersInit
  mute?: boolean
}

export default async function request<T = any>(config: Config | string): Promise<T> {
  if (typeof config === 'string') {
    return fetch(config).then(res => res.json())
  }
  let url = ''
  if (config.url.startsWith('http')) {
    url = config.url
  } else {
    const env = useRuntimeConfig()
    url = env.public.proxyTarget + '/api' + config.url
  }
  if (config.params) {
    url += '?' + qs.stringify(config.params)
  }

  const requestInit: RequestInit = { method: config.method || 'get', headers: config.headers || {} }
  if (config.data) {
    requestInit.body = JSON.stringify(config.data)
    requestInit.headers['Content-Type'] = 'application/json;charset=UTF-8'
  }

  const raw = await fetch(url, requestInit).catch(err => err)
  if (raw.status !== 200) {
    return Promise.reject(raw)
  }
  switch (config.responseType) {
    case 'blob':
      return raw.blob()
    case 'text':
      return raw.text()
    case 'raw':
      return raw.json()
    case 'json':
    default:
      const res = await raw.json()
      return res.data
  }
}
